package cn.flying.cloud.flow.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.flying.cloud.base.common.exception.CommonException;
import cn.flying.cloud.flow.annotation.FlowController;

/**
 * @author: admin
 * @date: 2024年12月17日 21:45
 * @version: 1.0
 */
@Component
public class FlowAuditForwardContext implements ApplicationContextAware {

    private final Map<String, FlowAuditForwardAbstract> beanMap = new ConcurrentHashMap<>();

    /**
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> objectMap = applicationContext.getBeansWithAnnotation(FlowController.class);
        objectMap.forEach((k, obj) -> {
            Class<?> clazz = obj.getClass();
            if (clazz.isAnnotationPresent(FlowController.class)) {
                FlowController annotation = clazz.getAnnotation(FlowController.class);
                if (StringUtils.isEmpty(annotation.name())) {
                    throw new CommonException("FlowController类指定的bean没有name属性");
                }
                beanMap.put(annotation.name(), (FlowAuditForwardAbstract) obj);
            }
        });
    }

    /**
     * 根据流程key获取对应的处理器
     *
     * @param key
     * @return
     */
    public FlowAuditForwardAbstract getBean(String key) {
        return beanMap.get(key);
    }
}
